struct DLinkedNode {
    int key, value;
    DLinkedNode* prev;
    DLinkedNode* next;
    DLinkedNode(): key(0), value(0), prev(nullptr),next(nullptr){}
    DLinkedNode(int _key, int _value):key(_key), value(_value), prev(nullptr),next(nullptr){}
};

class LRUCache {
private:
    unordered_map<int, DLinkedNode*> cache;
    DLinkedNode* head;  // 伪头节点
    DLinkedNode* tail;  // 伪尾节点
    int size;
    int capacity;
public:
    LRUCache(int _capacity) : capacity(_capacity), size(0) {
        head = new DLinkedNode();
        tail = new DLinkedNode();

        head->next = tail;
        tail->next = head;
    }
    
    int get(int key) {
        if(!cache.count(key)) {
            return -1;
        }

        DLinkedNode* node = cache[key];
        moveToHead(node);

        return node->value;
    }
    
    void put(int key, int value) {
        if(!cache.count(key)){
            // key不存在添加一个节点
            DLinkedNode* node = new DLinkedNode(key, value);
            // 
            cache[key] = node;
            // 保存的总数
            ++size;
            if(size > capacity){
                // 如果超出容量，删除双向链表的尾部节点
                DLinkedNode* removed = removeTail();
                cache.erase(removed->key);
                // 防止内存泄露
                delete removed;
                --size;
            }
        }else{
            DLinkedNode* node = cache[key];
            node->value = value;
            moveToHead(node);
        }
    }

    void addToHead(DLinkedNode* node){
        node->prev = head;
        node->next = head->next;

        head->next->prev = node;
        head->next = node;
    }

    void removeNode(DLinkedNode* node){
        node->prev->next = node->next;
        node->next->prev = node->prev;
    }

    void moveToHead(DLinkedNode* node){
        removeNode(node); //先删除。
        addToHead(node); //在添加到头结点。
    }

    DLinkedNode* removeTail() {
        DLinkedNode* node = tail->prev;
        removeNode(node);

        // 返回已经删除的节点信息。
        return node;
    }
};

/**
 * Your LRUCache object will be instantiated and called as such:
 * LRUCache* obj = new LRUCache(capacity);
 * int param_1 = obj->get(key);
 * obj->put(key,value);
 */
